package com.fzq.utils;

import com.fzq.config.MaskingStrategyFactory;
import com.fzq.config.Sensitive;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MaskUtil {
    /**
     * 对对象进行脱敏处理（默认方法）
     */
    public  void maskObject(Object obj) throws IllegalAccessException {
        if (obj == null) return;

        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Sensitive.class)) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value instanceof String) {
                    Sensitive annotation = field.getAnnotation(Sensitive.class);
                    String masked = MaskingStrategyFactory.getStrategy(annotation.type()).mask((String) value, annotation.pattern());
                    field.set(obj, masked);
                }
            }
        }
    }
}
